package com.zzu.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzu.base.common.enums.ResultStatusEnum;
import com.zzu.base.controller.permission.vo.PermissionPageReqVO;
import com.zzu.base.entity.PermissionDO;
import com.zzu.base.entity.RolePermissionDO;
import com.zzu.base.exception.ProcessException;
import com.zzu.base.mapper.PermissionMapper;
import com.zzu.base.mapper.RolePermissionMapper;
import com.zzu.base.service.PermissionService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper,PermissionDO> implements PermissionService {
    @Resource
    private PermissionMapper permissionMapper;
    @Resource
    private RolePermissionMapper rolePermissionMapper;
    @Override
    @Transactional
    public Boolean removePermission(Long id) {
        QueryWrapper<RolePermissionDO>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", id);
        rolePermissionMapper.delete(queryWrapper);
        return permissionMapper.deleteById(id) > 0;
    }

    @Override
    public Boolean update(PermissionDO permission) {
        QueryWrapper<PermissionDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("permission_code", permission.getPermissionCode());
        PermissionDO permissionDO= permissionMapper.selectOne(queryWrapper);
        if(permissionDO!=null){
            throw new  ProcessException(ResultStatusEnum.BAD_REQUEST,"已有重复权限代码");
        }
        return permissionMapper.updateById(permission)>0;
    }

    @Override
    public IPage<PermissionDO> getPermissionPage(PermissionPageReqVO permissionPageReqVO) {
        Page<PermissionDO>page = new Page<>(permissionPageReqVO.getPageNum(),permissionPageReqVO.getPageSize());
        QueryWrapper<PermissionDO> queryWrapper = new QueryWrapper<>();
        if (permissionPageReqVO.getPermissionName() != null) {
            queryWrapper.like("permission_name", permissionPageReqVO.getPermissionName());
        }
        return permissionMapper.selectPage(page,queryWrapper);
    }
}
